import AntModal from '@/components/pt/dialog/AntModal'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import {bizCostAdd,getBizCostDetail,bizCostEdit} from '@/api/biz/bizIncomePayment';
import { getInitData } from '@/api/biz/bizProduct'
import { listAllBizCustomer } from '@/api/biz/bizCustomer'
import moment from 'moment';
export default {
  name: 'CreateForm',
  props: {
    payOptions: {
      type: Array,
      required: false
    }
  },
  components: {
    AntModal,
    AdvanceTable
  },
  data () {
    return {
      open: false,
      closeDialog: true,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      loading: false,
      disabled: false,
      total: 0,
      id: undefined,
      multiple:false,
      formTitle: '',
      detailList:[],
      selectedRowKeys:[],
      selectedAccountRowKeys:[],
      inOutOptions:[],//收支类型
      multipleAccount:false,

      orderList:[],
      customerIdOptions:[],//往来单位
      columns: [
        {
          title: '销售单号',
          dataIndex:'orderNumber',
          align: 'center',
        },
        {
          title: '区域',
          dataIndex:'area',
          align: 'center'
        },
        {
          title: '日期',
          dataIndex:'orderDate',
          align: 'center'
        },
        {
          title: '金额',
          dataIndex:'totalAmount',
          align: 'center'
        },
        {
          title: '已结算额',
          dataIndex:'collectedAmount',
          align: 'center'
        },
        {
          title: '未结算额',
          align: 'center',
          scopedSlots: {
            customRender: 'nopaySlot'
          }
        },
        {
          title: '本次结算',
          dataIndex:'amount',
          align: 'center',
          scopedSlots: {
            customRender: 'curSlot'
          }
        }
      ],
      
      columns1: [
        {
          title: '收款账户',
          dataIndex:'payAccount',
          align: 'center',
          scopedSlots: {
            customRender: 'payAccount'
          }
        },
        {
          title: '收支金额',
          dataIndex:'payAmount',
          align: 'center',
          scopedSlots: {
            customRender: 'payAmount'
          }
        },
        {
          title: '备注',
          dataIndex:'remark',
          align: 'center',
          scopedSlots: {
            customRender: 'remark'
          }
        },
        {
          title: '操作',
          dataIndex:'operator',
          align: 'center',
          scopedSlots: {
            customRender: 'operator'
          }
        },
      ],
      // 表单参数
      form: {},
      rules: {
        customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],

        orderType: [{ required: true, message: '订单类型不能为空', trigger: 'blur' }],
        payAmount: [{ required: true, message: '收款金额不能为空', trigger: 'blur' }],
        payDate: [{ required: true, message: '请选择收款日期', trigger: 'blur' }],
        payAccount: [{ required: true, message: '请选择收款账户', trigger: 'blur' }],
        costType:[{ required: true, message: '请选择收支类型', trigger: 'blur' }]
      }
    }
  },
  filters: {},
  created () {
    this.listAllBizCustomer()
    
    getInitData('in_out_type').then(response => {
      this.inOutOptions = response.data.in_out_type
    })
  },
  computed: {},
  watch: {
  },
  mounted () {},
  methods: {
    getDetail(){
      this.loading = !this.loading
      getBizCostDetail(this.form.id).then(response => {
        if(response.code == 200) {
          this.orderList = response.data.bizCostDetailList
          this.loading = !this.loading
        }else{
          this.message.error(response.msg)
        }
      }).catch(()=>{
        
      this.loading = !this.loading
      })
    },
    handleAllocation(){
      let total = this.orderList.reduce((pre,cur)=>{
        return this.$toDecimal(pre + +cur.payAmount)
      },0)
      let nopayTotal = this.form.detailList.reduce((pre,cur)=>{
        return this.$toDecimal(pre + (this.$toDecimal(cur.totalAmount - +cur.collectedAmount)))
      },0)
      // 待付和应付总额相同，直接分配就可以了，不用判断
      if (nopayTotal === total) {
        this.form.detailList = this.form.detailList.map(v=>{
          let nopay = this.$toDecimal(+v.totalAmount - +v.collectedAmount)
          v.amount = nopay
          return v
        })
      }else{
        this.form.detailList = this.form.detailList.map(v=>{
          let nopay = this.$toDecimal(+v.totalAmount - +v.collectedAmount)
          if(+total >= +nopay && +nopay >0 ){
            v.amount = nopay
            total = this.$toDecimal(total - nopay)
          }else if(+total < +nopay && +total >=0){
            v.amount = total
            total = 0
          }else{
            v.amount = 0
          }
          return v
        })

      }
      this.amountChange()
    },
    onClose () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    handleAdd(){
      this.orderList.push({payAmount:0})
    },
    /**
     * @汇总收款金额
     */
    amountChange(){
      let total = this.orderList.reduce((pre,cur)=>{
        return this.$toDecimal(pre + +cur.payAmount)
      },0)
      this.$set(this.form,'payAmount',total)
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,

        payCode: undefined,
        supplierCode: undefined,

        supplierName: undefined,

        payAmount: undefined,

        purchaseDate: undefined,

        hasAmount: undefined,

        remark: undefined,

        payDate: undefined,

        payAccount: undefined

      }
    },
    handlePayment (row) {
      this.reset()
      this.open = true
      this.form = row
      this.$set(this.form,'payDate',moment(new Date()).format('YYYY-MM-DD'))
      if(this.form.id){
        this.formTitle = '编辑收支单';
        this.getDetail()
      }else{
        this.formTitle = '新增收支单';
      this.$set(this.form,'costType','1')
        this.handleAdd()
      }
    },
    listAllBizCustomer () {
      listAllBizCustomer().then((response) => {
        this.customerIdOptions = response.data
      }) 
    },
    /** 提交按钮 */
    submitForm: function (closeDialog) {
      this.closeDialog = closeDialog
      this.disabled = true
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.bizCostDetailList = this.orderList.map((v,i)=>(v.sort = i + 1,v))
          this.form.status = '0'
          const saveForm = JSON.parse(JSON.stringify(this.form))
          console.log('this.form.id :>> ', this.form.id);
          let func = this.form.id ? bizCostEdit : bizCostAdd
          func(saveForm).then(response => {
            if(response.code == 200){
              this.$message.success('操作成功', 3)
              this.$emit('ok')
              this.open = false
              this.$emit('close')
              this.disabled = false
            }else{
              this.disabled = false
            }
          }).catch(()=>{
            this.disabled = false
          })
        } else {
          this.disabled = false
          return false
        }
      })
    },
    back () {
      const index = '/biz/bizpayable/index'
      this.$router.push(index)
    },
    
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.multiple = selectedRowKeys.length
    },
    onAccountSelectChange(selectedRowKeys, selectedRows) {
      this.selectedAccountRowKeys = selectedRowKeys
      this.multipleAccount = selectedRowKeys.length
    },
    handleDelete(){
      if (!this.selectedAccountRowKeys.length) {
        this.$message.error(
          '请选择要删除的数据',
          3
        )
        return
      }
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk: () => {
          this.orderList = this.orderList.filter((v, index) => !this.selectedAccountRowKeys.includes(index) && !this.selectedAccountRowKeys.includes(v.id))
          this.selectedAccountRowKeys = []
          this.multipleAccount = false
          this.$message.success(
            '删除成功',
            3
          )
        }
      })
    },

  }
}
